package com.example.zhish.gobang.view;

import android.app.AlertDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Point;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

import com.example.zhish.gobang.R;
import com.example.zhish.gobang.bean.Constant;
import com.example.zhish.gobang.bean.GobangCheckboard;
import com.example.zhish.gobang.bean.NovicePlayer;
import com.example.zhish.gobang.util.GobangUtil;

/**
 * Created by qianjun on 2016/5/2.
 */
public class GobangPanel extends View {

    private Paint mPaint = new Paint();


    private int mPanelwidth;
    private float mLineheight;
    private Bitmap mWhitePiece;
    private Bitmap mBlackPiece;
    private float ratioPieceOfLineHeight = 3 * 1.0f / 4;
    private GobangCheckboard gobangCheckboard;
    public static int MAX_PIECES_WIN = Constant.FIVE_PIECES_WIN;
    private int table_x = Constant.SMALL_CHECKBOARD_X;
    private int table_y = Constant.SMALL_CHECKBOARD_Y;
    private int[][] table;
    //对话框
    private AlertDialog.Builder builder;
    //为true时，表示黑棋下
    private boolean mIsBlackOrWhite = true;
    //获胜者
    private int winner = Constant.NO_VICTORY_OR_DEFEAT;

    //机器人棋手
    private NovicePlayer novicePlayer;

    //工具类
    private GobangUtil gobangUtil;

    //对弈模式：人人还是人机，暂时写成人机
    private int chessMode = Constant.HUMAN_PK_ROBOT;


    //初始化
    public void init() {
        gobangCheckboard = GobangCheckboard.getGobangCheckboard(table_x, table_y);
        gobangCheckboard.init();
        table = gobangCheckboard.table;
        //画笔设置
        mPaint.setAlpha(10);
        mPaint.setColor(Color.rgb(0x8b, 0x8b, 0x83));
        mPaint.setAntiAlias(true);
        mPaint.setDither(true);
        mPaint.setStyle(Paint.Style.STROKE);

        //图片加载
        mWhitePiece = BitmapFactory.decodeResource(getResources(), R.drawable.stone_w2);
        mBlackPiece = BitmapFactory.decodeResource(getResources(), R.drawable.stone_b1);
        //初始化机器人棋手
        novicePlayer = new NovicePlayer();

        //工具类初始化
        gobangUtil = GobangUtil.getGobangUtil(table_x, table_y);
    }

    //构造函数
    public GobangPanel(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);

        int width = Math.min(widthSize, heightSize);
        if (widthMode == MeasureSpec.UNSPECIFIED) {
            width = heightSize;
        } else if (heightMode == MeasureSpec.UNSPECIFIED) {
            width = widthSize;
        }

        setMeasuredDimension(width, width);

    }

    @Override
    protected void onSizeChanged(int w, int h, int oldw, int oldh) {
        super.onSizeChanged(w, h, oldw, oldh);

        mPanelwidth = w;
        mLineheight = mPanelwidth * 1.0f / table_x;

        int piecewidth = (int) (mLineheight * ratioPieceOfLineHeight);
        mWhitePiece = Bitmap.createScaledBitmap(mWhitePiece, piecewidth, piecewidth, false);
        mBlackPiece = Bitmap.createScaledBitmap(mBlackPiece, piecewidth, piecewidth, false);

    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        drawBoard(canvas);
        //canvas.drawBitmap(mBlackPiece, ( (1 - ratioPieceOfLineHeight) / 2) * mLineheight, ((1 - ratioPieceOfLineHeight) / 2) * mLineheight, null);
        drawPieces(canvas);
    }

    //绘制棋盘
    private void drawBoard(Canvas canvas) {
        int w = mPanelwidth;
        float lineHeight = mLineheight;
        for (int i = 0; i < table_x; i++) {
            int startX = (int) (lineHeight / 2);
            int endX = (int) (w - lineHeight / 2);

            int y = (int) ((0.5 + i) * lineHeight);
            canvas.drawLine(startX, y, endX, y, mPaint);
            canvas.drawLine(y, startX, y, endX, mPaint);

        }
    }

    //绘制棋子
    private void drawPieces(Canvas canvas) {
        for (int i = 0; i < table_x; i++) {
            for (int j = 0; j < table_y; j++) {
                if (table[i][j] == Constant.WHITE_PIECE) {
                    canvas.drawBitmap(mWhitePiece, (i + (1 - ratioPieceOfLineHeight) / 2) * mLineheight, (j + (1 - ratioPieceOfLineHeight) / 2) * mLineheight, null);
                } else if (table[i][j] == Constant.BLACK_PIECE) {
                    canvas.drawBitmap(mBlackPiece, (i + (1 - ratioPieceOfLineHeight) / 2) * mLineheight, (j + (1 - ratioPieceOfLineHeight) / 2) * mLineheight, null);
                }
            }
        }
    }

    //重写触屏点击事件
    @Override
    public boolean onTouchEvent(MotionEvent event) {
        if (gobangCheckboard.isStop) {
            return false;
        }

        switch (event.getAction()) {
            case MotionEvent.ACTION_UP:

                //人机对弈模式
                if (chessMode == Constant.HUMAN_PK_ROBOT) {
                    if (mIsBlackOrWhite) {
                        int x = (int) (event.getX() / mLineheight);
                        int y = (int) (event.getY() / mLineheight);
                        Point point = new Point(x, y);
                        if (table[x][y] == Constant.NO_PIECES) {
                            table[x][y] = Constant.BLACK_PIECE;
                            mIsBlackOrWhite = !mIsBlackOrWhite;
                            //通知重新绘制棋盘
                            this.invalidate();
                            //判断输赢
                            winner = gobangUtil.isWin(point);
                            if (winner != Constant.NO_VICTORY_OR_DEFEAT) {
                                showResult(winner);
                            }


                            //机器人下棋
                            Point robotPoint = novicePlayer.findBestPoint(table_x, table_y);
                            table[robotPoint.x][robotPoint.y] = Constant.WHITE_PIECE;
                            mIsBlackOrWhite = !mIsBlackOrWhite;
                            //判断输赢
                            winner = gobangUtil.isWin(robotPoint);
                            if (winner != Constant.NO_VICTORY_OR_DEFEAT) {
                                showResult(winner);
                            }
                        }
                    }


                } else if (chessMode == Constant.HUMAN_PK_HUMAN) {//人人对弈模式
                    int x = (int) (event.getX() / mLineheight);
                    int y = (int) (event.getY() / mLineheight);
                    Point point = new Point(x, y);
                    //如果当前位置没有棋子，则判断是白子还是黑子，并写入棋盘
                    if (table[x][y] == Constant.NO_PIECES) {
                        if (mIsBlackOrWhite) {
                            table[x][y] = Constant.BLACK_PIECE;

                        } else {
                            table[x][y] = Constant.WHITE_PIECE;
                        }
                        mIsBlackOrWhite = !mIsBlackOrWhite;
                        //通知重新绘制棋盘
                        this.invalidate();
                        //判断输赢
                        winner = gobangUtil.isWin(point);
                        if (winner != Constant.NO_VICTORY_OR_DEFEAT) {
                            showResult(winner);
                        }


                    }
                }

                break;
        }

        return true;
    }

    //显示胜负信息
    private void showResult(int winner) {
        //对局结束标志
        gobangCheckboard.isStop = true;
        switch (winner) {
            case Constant.BLACK_WINNER:
                Toast.makeText(getContext(), "黑棋获胜！", Toast.LENGTH_LONG).show();
                break;
            case Constant.WHITE_WINNER:
                Toast.makeText(getContext(), "白棋获胜！", Toast.LENGTH_LONG).show();
                break;
            case Constant.NO_WINNER:
                Toast.makeText(getContext(), "平局！", Toast.LENGTH_LONG).show();
                break;

        }
    }


}
